<template>
  <div class="main" :style="mainStyle">
    <!-- 饼图 -->
    <!-- 为ECharts准备一个具备大小（宽高）的Dom -->
    <div :id="props.id" class="pie" :style="echartsStyle"></div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
const { proxy } = getCurrentInstance();

let props = defineProps([
  "id",
  "size",
  "seriesData",
  "name",
  "titleText",
  "subtext",
  "type",
  "roseType",
  "formatter", // 自定义label格式化器
]);
const emit = defineEmits(["fatherMethods"]);

let colors = computed(() => {
  let arr = ["#5470c6", "#3ba272", "#ee6666", "#fac858", "#73c0de", "#3ba272"];
  return arr;
  return proxy.$utils.shuffle(arr);
});

let echartsStyle = computed(() => {
  if (props.size) return { height: `${props.size}px`, width: "100%" };
  return {
    position: "absolute",
    top: 0,
    left: 0,
    width: "100%",
    height: "100%",
  };
});

let mainStyle = computed(() => {
  if (props.size) return;
  return {
    width: "100%",
    height: 0,
    "padding-top": "100%",
    position: "relative",
  };
});

let init = () => {
  let myChart = echarts.init(document.getElementById(props.id));
  myChart.clear(); // 适用于大数据量的切换时图表绘制错误,先清空在重绘

  //点击选中
  myChart.on("click", function (e) {
    emit("fatherMethods", e);
  });

  let option = {
    title: {
      text: props.titleText,
      subtext: props.subtext,
      left: "center",
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      show: false,
      orient: "vertical",
      left: "left",
      formatter: (name) => {
        // 在这里你可以对名字进行截断，比如：
        return name.length > 15 ? name.slice(0, 15) + "..." : name;
      },
    },
    //color: colors.value,
    series: [
      {
        name: props.name,
        type: "pie",
        label: {
          show: false,
          position: "center",
          normal: {
            formatter: props.formatter ? props.formatter : "{b}：{d}%",
          },
        },
        avoidLabelOverlap: false,
        padAngle: 5,
        radius: props.type == "annular" ? ["40%", "70%"] : "40%",
        data: props.seriesData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };
  if (props.roseType) {
    option["roseType"] = props.roseType;
  }
  myChart.setOption(option);
};

watch(
  () => props.seriesData,
  (newValue, oldValue) => {
    if (newValue && newValue.length) {
      init();
    }
  },
  { immediate: true, deep: true }
);
</script>



<style lang="scss" scoped>
</style>
